﻿using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI;

namespace Liebrand.OfficeFileTypes
{
    public class OfficeFileTypeMenuItem : WebControl
    {
        #region Declarations
        private const string WordFileTypes = "(.dot|.dotx|.doc|.docx|.docm|.dotm)";
        private const string ExcelFileTypes = "(.xlsx|.xls|.xlsm|.xltx|.xltm|.xlsb|.xlam)";
        private const string PowerPointFileTypes = "(.pot|.potx|.ppt|.pptx|.pptm|.ppsx|.potm|.ppam)";
        #endregion

        #region Properties

        private SPFolder folder = null;
        private SPList list = null;

        protected SPFolder CurrentFolder
        {
            get
            {
                string folderUrl = base.Page.Request.QueryString["RootFolder"];

                if (SPContext.Current.List == null) // menu is being displayed in a ListViewWebPart
                {
                    this.folder = CurrentList.RootFolder;
                }
                else if (!string.IsNullOrEmpty(folderUrl))
                {
                    this.folder = SPContext.Current.Web.GetFolder(folderUrl);
                }
                else
                {
                    this.folder = CurrentList.RootFolder;
                }

                return this.folder;
            }
        }

        protected SPList CurrentList
        {
            get
            {
                if (this.list == null)
                {
                    if (SPContext.Current.List == null)
                    {
                        this.list = SPContext.Current.Web.Lists[new Guid(CurrentListViewWebPart.ListName)];
                    }
                    else
                    {
                        this.list = SPContext.Current.List;
                    }
                }

                return list;

            }
        }

        protected ListViewWebPart CurrentListViewWebPart
        {
            get
            {
                string listId = string.Empty;
                Control control = this.Parent;
                while (control != null && control.GetType().Name != "ListViewWebPart")
                {
                    control = control.Parent;
                }

                if (control == null)
                    throw new SPException("Unable to determine list for menu");

                return control as ListViewWebPart;

            }
        }

        protected ISecurableObject CurrentSecurableItem
        {
            get
            {
                if (CurrentFolder.Item == null)
                    return this.list;
                else
                    return CurrentFolder.Item;
            }
        }
        protected IList<SPContentType> ContentTypes
        {
            get
            {
                if (CurrentFolder.UniqueContentTypeOrder == null)
                    return CurrentFolder.ContentTypeOrder;
                else
                    return CurrentFolder.UniqueContentTypeOrder;
            }
        }
        #endregion

        #region Overrides
        protected override void CreateChildControls()
        {

            bool hasAddListItems = false;

            if (!SPContext.Current.Web.CurrentUser.IsSiteAdmin)
            {

                hasAddListItems = CheckForAddListItems(CurrentSecurableItem.AllRolesForCurrentUser);

                if (!hasAddListItems)
                    return;
            }

            MenuItemTemplate officeFileType;

            bool hidden = true;

            string documentTemplate = string.Empty;
            SPContentType documentContentType = CurrentList.ContentTypes["Document"];
            documentTemplate = documentContentType.DocumentTemplate;

            foreach (SPContentType item in this.ContentTypes)
            {
                if (item.Id == documentContentType.Id)
                {
                    hidden = false;
                    break;
                }
            }

            bool match = false;
            Regex regex = new Regex(WordFileTypes, RegexOptions.IgnoreCase);
            match = regex.IsMatch(documentTemplate);
            if ((match && hidden) || (!match))
            {
                officeFileType = CreateOfficeFileType(SPUtility.GetLocalizedString("$Resources:WordTitle", "officefiletypes", SPContext.Current.Web.Language), "/_layouts/images/lg_icdoc.gif", 400, "Word.Document.8");
                this.Controls.Add(officeFileType);
            }

            regex = new Regex(ExcelFileTypes, RegexOptions.IgnoreCase);
            match = regex.IsMatch(documentTemplate);
            if ((match && hidden) || (!match))
            {
                officeFileType = CreateOfficeFileType(SPUtility.GetLocalizedString("$Resources:ExcelTitle", "officefiletypes", SPContext.Current.Web.Language), "/_layouts/images/lg_icxls.gif", 401, "Excel.Sheet.8");
                this.Controls.Add(officeFileType);
            }

            regex = new Regex(PowerPointFileTypes, RegexOptions.IgnoreCase);
            match = regex.IsMatch(documentTemplate);
            if ((match && hidden) || (!match))
            {
                officeFileType = CreateOfficeFileType(SPUtility.GetLocalizedString("$Resources:PowerPointTitle", "officefiletypes", SPContext.Current.Web.Language), "/_layouts/images/lg_icppt.gif", 402, "PowerPoint.Show.8");
                this.Controls.Add(officeFileType);
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {
            RenderChildren(output);
        }
        #endregion

        #region Methods
        private static bool CheckForAddListItems(SPRoleDefinitionBindingCollection roles)
        {
            foreach (SPRoleDefinition role in roles)
            {
                if ((role.BasePermissions & SPBasePermissions.AddListItems) != 0)
                    return true;
            }

            return false;
        }

        private MenuItemTemplate CreateOfficeFileType(string title, string imageUrl, int sequence, string programId)
        {
            MenuItemTemplate template = new MenuItemTemplate();
            template.Text = title;
            template.Description = string.Format(SPUtility.GetLocalizedString("$Resources:MenuDescription", "officefiletypes", SPContext.Current.Web.Language), title);
            template.ID = "OfficeFileType";
            template.Sequence = sequence;
            template.ImageUrl = imageUrl;

            string clickScript = string.Format("createNewDocumentWithProgID('{0}','{1}','SharePoint.OpenDocuments', false)", programId, GetAbsoluteFullUrl());
            template.ClientOnClickScript = clickScript;

            return template;
        }

        private string GetAbsoluteFullUrl()
        {
            return SPContext.Current.Web.Url + "/" + CurrentFolder.Url;
        }


        #endregion

    }
}
